M = {}

local newPlayer = function(x, y)
    --local player = display.newRect(x, y, 10, 10)
    local player = display.newImage("kiwi.png")
    player.x = x
    player.y = y
    physics.addBody(player, "dinamic", { density = 0.1, friction = 0.3, bounce = 0.3 })
    player.tilt = 0
    player.isFixedRotation = true
    player.baloons = {}
    player.type= "player"
    --player:setFillColor(0, 0, 255)


    local textObj = display.newText(player.tilt, 200, 0)

    --impulso
    local function impulsar(event)
        if (event.phase == "began") then
            player:applyLinearImpulse(0, -0.13, player.x, player.y)
            textObj.text = player.tilt
        end
    end

    Runtime:addEventListener("touch", impulsar)

    --update frame
    local function update(event)
        if (player.tilt > 0.2) then player.tilt = 0.2 end
        if (player.tilt < -0.2) then player.tilt = -0.2 end
        vx, vy = player:getLinearVelocity()
        player:setLinearVelocity(player.tilt * 200, vy)
       --player:setLinearVelocity(0.05 * 200, vy)
        player.xScale = -player.tilt/math.abs(player.tilt)
    end

    Runtime:addEventListener("enterFrame", update)

    --tilt
    local function onTilt(event)
        player.tilt = -event.yGravity
    end

    Runtime:addEventListener("accelerometer", onTilt)

    return player
end

M.newPlayer = newPlayer

return M